package com.weilx959.spt.core.component;

import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.validation.base.ValidatorBase;
import com.weilx959.spt.core.utils.FXMLUtil;
import com.weilx959.spt.core.utils.Try;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import org.apache.commons.lang3.StringUtils;

/**
 * 密码输入框控件
 *
 * @author weilx
 * @since 2024年6月2日
 */
public class PasswordFormItemControl extends ValidatorFormItemControl<String> {
    private static final String XML = "/assets/fxml/component/password-form-control.fxml";

    @FXML
    private Label labelControl;

    @FXML
    private JFXPasswordField passwordFieldControl;

    public PasswordFormItemControl() {
        super();
        initialize();
    }

    @Override
    public Try<String> validate() {
        return Try.of(() -> {
            if (!passwordFieldControl.validate()) {
                throw new IllegalStateException(passwordFieldControl.getActiveValidator().getMessage());
            }
        });
    }

    @Override
    public boolean isModified() {
        return !StringUtils.equals(oldValue, getValue());
    }

    @Override
    public void addValidator(ValidatorBase... validator) {
        this.passwordFieldControl.setValidators(validator);
    }

    public EventHandler<ActionEvent> getOnAction() {
        return passwordFieldControl.getOnAction();
    }

    public void setOnAction(EventHandler<ActionEvent> onAction) {
        passwordFieldControl.setOnAction(onAction);
    }

    private void initialize() {
        // load
        FXMLUtil.loadControl(this, XML);
        // 输入框
        passwordFieldControl.textProperty().bindBidirectional(valueProperty());
    }

    // builder
    public static PasswordFormItemControlBuilder builder() {
        return new PasswordFormItemControlBuilder();
    }

    public static class PasswordFormItemControlBuilder
        extends ValidatorFormItemControlBuilder<String, PasswordFormItemControl, PasswordFormItemControlBuilder> {
        @Override
        protected PasswordFormItemControl newFormItemControl() {
            return new PasswordFormItemControl();
        }

        @Override
        protected PasswordFormItemControlBuilder self() {
            return this;
        }
    }
}
